<template>
  <div class="calculate-group">
    <div class="factory-calculate-list">
      <div class="search-header">
        <el-input v-model="searchInput" size="small" placeholder="输入搜索关键字" @keyup.13.native="onSearch">
          <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="searchInput.length"></i>
          <el-button type="primary" slot="append" icon="el-icon-search" @click="onSearch"></el-button>
        </el-input>
        <el-tooltip effect="dark" content="新建分组" placement="top">
          <el-button type="primary" class="add-btn" @click="editGroup('add')">
            <icon-svg name="iconGroup"></icon-svg>
          </el-button>
        </el-tooltip>
      </div>
      <el-collapse v-model="activeCollapse" accordion v-if="groupList.length">
        <el-collapse-item v-for="(item, index) in groupList" :key="item.groupId" :name="item.groupId">
          <div slot="title" class="group-title">
            <i
              class="icon-toggle"
              :class="activeCollapse === item.groupId ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
            ></i>
            <el-tooltip effect="dark" :content="item.groupNm" placement="top-start">
              <span class="name">{{ item.groupNm }}</span>
            </el-tooltip>
            <el-popover placement="right-start" width="120" trigger="hover" popper-class="tag-group-handler">
              <ul>
                <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 0 }))">
                  <i class="el-icon-circle-plus-outline"></i>标签运算
                </li>
                <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 1 }))">
                  <i class="el-icon-circle-plus-outline"></i>SQL创建
                </li>
                <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 2 }))">
                  <i class="el-icon-circle-plus-outline"></i>逻辑分群
                </li>
                <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 3 }))">
                  <i class="el-icon-circle-plus-outline"></i>单一型指标
                </li>
                <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 4 }))">
                  <i class="el-icon-circle-plus-outline"></i>复合型指标
                </li>
                <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 5 }))">
                  <i class="el-icon-circle-plus-outline"></i>交叉型指标
                </li>
                <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 6 }))">
                  <i class="el-icon-circle-plus-outline"></i>比率型指标
                </li>
                <!-- <li>
                  <i class="el-icon-circle-plus-outline"></i>规则创建
                  <i class="el-icon-arrow-right"></i>
                  <ol>
                    <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 2 }))">
                      <i class="el-icon-circle-plus-outline"></i>逻辑分群
                    </li>
                    <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 3 }))">
                      <i class="el-icon-circle-plus-outline"></i>单一型指标
                    </li>
                    <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 4 }))">
                      <i class="el-icon-circle-plus-outline"></i>复合型指标
                    </li>
                    <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 5 }))">
                      <i class="el-icon-circle-plus-outline"></i>交叉型指标
                    </li>
                    <li @click="handleAdd(Object.assign({}, item, { tagFactoryType: 6 }))">
                      <i class="el-icon-circle-plus-outline"></i>比率型指标
                    </li>
                  </ol>
                </li> -->
                <template v-if="item.groupId">
                  <li @click="editGroup('edit', item)">
                    <icon-svg name="iconFacEdit" class="el-edit"></icon-svg>
                    编辑分组
                  </li>
                  <li @click="deleteGroup(item)">
                    <icon-svg name="iconDelete" class="el-delete"></icon-svg>
                    删除分组
                  </li>
                </template>
              </ul>
              <i class="el-icon-more group-handler" slot="reference"></i>
            </el-popover>
          </div>
          <div class="factory-list">
            <template v-if="item.page.results.length">
              <ul class="list-wrap">
                <li
                  class="list-item"
                  :class="{ 'is-active': tag.tagId === selectTag.tagId }"
                  v-for="tag in item.page.results"
                  :key="tag.tagId"
                  @click="selectItem(tag)"
                >
                  <icon-svg
                    :name="tag.tagFactoryType > 1 ? 'iconRole' : tag.tagFactoryType === 1 ? 'iconSql' : 'iconCalculate'"
                    :class="{ 'calcalute-svg': tag.tagFactoryType === 0, 'sql-svg': tag.tagFactoryType === 1 }"
                  ></icon-svg>
                  <span class="list-name elli">{{ tag.tagNm }}</span>
                </li>
              </ul>
              <el-pagination
                style="text-align: right"
                :current-page="item.page.params.currentPageNum"
                :page-size="item.page.params.pageSize"
                background
                layout="total, prev, pager, next"
                :total="item.page.totalSize"
                :pager-count="5"
                small
                @current-change="handleCurrentChange($event, index)"
              >
              </el-pagination>
            </template>
            <div class="no-record" v-else>
              <img src="~@/assets/img/no_records.png" /><br />
              暂无内容
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
      <div class="no-record" v-else>
        <img src="~@/assets/img/no_records.png" /><br />
        暂无内容
      </div>
    </div>
    <div class="factory-calculate-wrapper">
      <div class="calculate-wrapper" v-if="selectTag.tagId">
        <calculate-header :tag="selectTag" move release repush @callback="getList">
          <template #pre>
            <el-button size="mini" @click="handleEdit('edit')" :class="{ disabled: selectTag.releaseStatus == 2 }">
              <icon-svg name="iconFacEdit"></icon-svg>
              编辑
            </el-button>
          </template>
          <template #suffix>
            <el-button size="mini" @click="handleDelete">
              <icon-svg name="iconDelete"></icon-svg>
              删除
            </el-button>
          </template>
        </calculate-header>
        <div class="calculate-content tag-scrollbar">
          <calculate-preview
            ref="calculatePreview"
            :config="selectTag"
            :dataLabs="JSON.parse(selectTag.tagConfigJson).configJson"
            :results="JSON.parse(selectTag.previewResults)"
            showStory
            :tagStory="selectTag.tagStory"
            v-if="selectTag.tagFactoryType === 0"
          ></calculate-preview>
          <sql-preview v-if="selectTag.tagFactoryType === 1" :config="selectTag"></sql-preview>
          <logic-preview v-if="selectTag.tagFactoryType === 2" :config="selectTag"></logic-preview>
          <single-preview v-if="selectTag.tagFactoryType === 3" :config="selectTag"></single-preview>
          <compose-preview v-if="selectTag.tagFactoryType === 4" :config="selectTag"></compose-preview>
          <cross-preview v-if="selectTag.tagFactoryType === 5" :config="selectTag"></cross-preview>
          <rate-preview v-if="selectTag.tagFactoryType === 6" :config="selectTag"></rate-preview>
        </div>
      </div>
      <div class="no-record" v-else>
        <template v-if="!loading">
          <img src="~@/assets/img/no_records.png" /><br />
          暂无内容
        </template>
        <div class="loading-box" v-else v-loading="loading" element-loading-spinner="el-icon-loading"></div>
      </div>
    </div>
    <tag-group ref="tagGroup" @callback="getGroupList"></tag-group>
  </div>
</template>

<script>
import calculateHeader from '../components/calculate-content-header'
import calculatePreview from './calculate-preview'
import sqlPreview from '../sql/sql-preview'
import logicPreview from '../role/logic/logic-preview'
import singlePreview from '../role/single/single-preview'
import composePreview from '../role/compose/compose-preview'
import crossPreview from '../role/cross/cross-preview'
import ratePreview from '../role/rate/rate-preview'
import devired from '../devired.js'
export default {
  components: {
    calculateHeader,
    calculatePreview,
    sqlPreview,
    logicPreview,
    singlePreview,
    composePreview,
    crossPreview,
    ratePreview
  },
  data() {
    return {
      loading: false,
      activeCollapse: -1,
      groupList: [],
      searchInput: '',
      selectTag: {}
    }
  },
  created() {
    this.getGroupList()
  },
  watch: {
    activeCollapse() {
      // this.selectTag = {}
      this.getList()
    }
  },
  methods: {
    getGroupList() {
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagDerivedGroup/getAllGroup/2'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.groupList = [{ groupId: 0, groupNm: '默认分组' }, ...data.data]
          this.groupList.forEach(item => {
            item.page = {
              results: [],
              params: {
                ascs: [],
                descs: [],
                currentPageNum: 1,
                pageSize: 10,
                queryParams: {
                  groupId: item.groupId
                },
                descPriority: false
              },
              totalSize: 0
            }
          })
          if (this.selectTag.tagId) this.getList()
          else this.activeCollapse = 0
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getList() {
      const group = this.groupList.find(item => item.groupId === this.activeCollapse)
      const index = this.groupList.findIndex(item => item.groupId === this.activeCollapse)
      if (group) {
        let params = group.page.params
        if (this.searchInput.trim()) params.queryParams.tagNm = this.searchInput.trim()
        else delete params.queryParams.tagNm
        this.$ajax({
          url: this.$ajax.setUrl('der/derTagCalculation/selectTagInfo'),
          method: 'get',
          params: this.$ajax.setParams(group.page.params)
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.groupList[index].page.results = data.data.records
            this.groupList[index].page.totalSize = data.data.totalSize
            let maxPageNum = Math.ceil(data.data.totalSize / group.page.params.pageSize) || 1
            if (group.page.params.currentPageNum > maxPageNum) {
              group.page.params.currentPageNum = maxPageNum
              this.getList()
            }
            if (data.data.records.length && !this.selectTag.tagId) this.selectItem(data.data.records[0])
            else {
              if (this.selectTag.tagId) {
                const target = this.groupList[index].page.results.find(item => item.tagId === this.selectTag.tagId)
                if (target) this.selectTag = target
              }
            }
            this.$forceUpdate()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      }
    },
    searchMyGroup() {
      this.$ajax({
        url: this.$ajax.setUrl(`der/derTagCalculation/getScreenPageGroup/${this.searchInput}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.groupList = data.data
          this.groupList.forEach(item => {
            item.page = {
              results: [],
              params: {
                ascs: [],
                descs: [],
                currentPageNum: 1,
                pageSize: 10,
                queryParams: {
                  groupId: item.groupId
                },
                descPriority: false
              },
              totalSize: 0
            }
          })
          if (!this.selectTag.tagId && this.groupList.length) this.activeCollapse = this.groupList[0].groupId
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    onSearch() {
      this.activeCollapse = ''
      this.selectTag = {}
      if (!this.searchInput) {
        this.getGroupList()
      } else {
        this.searchMyGroup()
      }
    },
    clearSearch() {
      this.searchInput = ''
      this.selectTag = {}
      this.onSearch()
    },
    handleCurrentChange(num, index) {
      this.groupList[index].page.params.currentPageNum = num
      this.selectTag = {}
      this.getList()
    },
    selectItem(item) {
      this.selectTag = item
    },
    handleAdd(item) {
      this.handleEdit('add', item)
    },
    handleEdit(type = 'add', item = {}) {
      if (!item.hasOwnProperty('tagFactoryType') && this.selectTag.releaseStatus == 2) {
        this.$message.info('标签正在审核中！')
        return
      }
      let routeParams = {
        name: devired.filterRouteName(
          item.hasOwnProperty('tagFactoryType') ? item.tagFactoryType : this.selectTag.tagFactoryType
        )
      }
      let query = {}
      if (type === 'edit') {
        query = { tagId: this.selectTag.tagId, groupId: this.selectTag.groupId }
      } else {
        query = { groupId: item.groupId }
      }
      routeParams.query = query
      this.$router.push(routeParams)
    },
    handleDelete() {
      this.$confirm(`确定删除计算型标签【${this.selectTag.tagNm}】？`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        const url =
          this.selectTag.tagFactoryType === 1
            ? `der/derTagSqlCreate/deleteSqlStatement/${this.selectTag.tagId}`
            : `der/derTagCalculation/Delete/${this.selectTag.tagId}`
        this.$ajax({
          url: this.$ajax.setUrl(url),
          method: 'delete',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.selectTag = {}
            this.getList()
            this.$message.success(data.msg)
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    editGroup(type = 'add', item = {}) {
      this.$refs.tagGroup.showDialog({ type, groupId: item.groupId, groupNm: item.groupNm, groupType: 2 })
    },
    deleteGroup(item) {
      this.$confirm(`是否确认删除分组【${item.groupNm}】?`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`ast/astTagDerivedGroup/${item.groupId}`),
          method: 'delete',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            this.getGroupList()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss">
.calculate-group {
  height: 100%;
  .factory-calculate-list {
    width: 320px;
    padding: 0 0px 24px 36px;
    background-color: #f6f7f8;
    position: absolute;
    top: 0;
    left: 10px;
    bottom: 0;
    overflow: auto;
    box-shadow: 1px 1px 2px #ddd;
    .search-header {
      display: flex;
      align-items: center;
      justify-content: space-around;
      padding: 0 8px;
      margin-bottom: 10px;
      .el-input {
        width: 200px;
      }
      .el-input__suffix {
        top: 5px;
      }
      .el-input__suffix-inner {
        font-size: 18px;
        color: #4d82e9;
      }
    }
    .add-btn {
      height: 33px;
      margin-left: 10px;
      padding: 0 15px;
      color: #455fbc;
      background-color: #e4eafe;
      border-color: #e4eafe;
      svg {
        width: 18px;
        height: 18px;
      }
    }
  }
  .el-input-group__append {
    padding: 0 15px;
    color: #fff;
    background-color: #455fbc;
    border-color: #455fbc;
    i {
      font-size: 17px;
    }
  }
  .el-collapse-item__header {
    font-size: 16px;
    height: 45px;
    padding: 0 10px;
    line-height: 45px;
    &:hover {
      background-color: #efefef;
    }
  }
  .el-collapse-item__arrow {
    display: none;
  }
  .icon-toggle {
    font-size: 18px;
    color: #4d82e9;
  }
  .el-collapse-item__content {
    padding-bottom: 0;
  }
  .group-title {
    width: 100%;
    position: relative;
    padding-right: 20px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    .name {
      margin-left: 10px;
    }
  }
  .group-handler {
    color: #4d82e9;
    position: absolute;
    top: 15px;
    right: 0;
  }
  .list-wrap {
    padding: 10px;
  }
  .list-item {
    padding: 10px;
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    cursor: pointer;
    &:hover {
      color: #778cda;
      background-color: #efefef;
    }
    &.is-active {
      color: #778cda;
      background-color: #efefef;
    }
    .list-name {
      margin-left: 8px;
      flex: 1;
    }
    .list-creator,
    .list-time {
      margin-left: 6px;
      font-size: 12px;
      color: #8c8b8b;
    }
    svg {
      width: 18px;
      height: 18px;
    }
    .calcalute-svg {
      width: 16px;
      height: 16px;
    }
    .sql-svg {
      width: 20px;
      height: 20px;
    }
  }
  .factory-calculate-wrapper {
    height: 100%;
    padding-left: 350px;
    background-color: #fff;
    .calculate-wrapper {
      height: 100%;
    }
  }
  .no-record {
    padding: 20px 0;
    text-align: center;
    img {
      margin-bottom: 10px;
    }
  }
}
</style>
